package com.anjubao.parking.municipal.parkinglot.service;

import com.anjubao.parking.municipal.parkinglot.dto.ParkingTrendFailuresDto;
import com.anjubao.parking.municipal.parkinglot.mapper.ParkingStatFailuresMapper;
import com.anjubao.parking.municipal.parkinglot.model.ParkingLotDeviceLog;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.Period;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author anjubao
 */
@Service
public class ParkingTrendFailuresService extends ServiceImpl<ParkingStatFailuresMapper, ParkingLotDeviceLog> {

    @Resource
    private ParkingStatFailuresMapper parkingStatFailuresMapper;
    private static final Integer DAY = 30;

    /**
     * 最近30天运维事件趋势
     * @param cityId
     * @return
     */
    public List<ParkingTrendFailuresDto> getTrendFailures(Integer cityId) {
        //查询数据库近30天运维事件
        List<ParkingTrendFailuresDto> trendFailuresDtoList = parkingStatFailuresMapper.getTrendFailures(cityId);
        //遍历获取30天日期的结果集
        for (int i = 1; i <= DAY; i++) {
            //得到近30天每天的日期
            LocalDate eventTime = LocalDate.now().minusDays(i);
            ParkingTrendFailuresDto parkingTrendFailuresDto = new ParkingTrendFailuresDto();
            //初始化flat用来记录该天是否存在数据
            Boolean flat = false;
            for (ParkingTrendFailuresDto trendFailuresDto : trendFailuresDtoList) {
                //判断集合中该时间是否存在数据,存在就将flat置为true并跳出循环
                if (trendFailuresDto.getEventTime().isEqual(eventTime)) {
                    flat = true;
                    break;
                }
            }
            //时间不存在,该天数据置为0
            if (!flat) {
                parkingTrendFailuresDto.setEventTime(eventTime);
                parkingTrendFailuresDto.setFailuresNum(0);
                trendFailuresDtoList.add(parkingTrendFailuresDto);
            }
        }
        //将30天的记录排序
        Collections.sort(trendFailuresDtoList, new Comparator<ParkingTrendFailuresDto>() {
            @Override
            public int compare(ParkingTrendFailuresDto o1, ParkingTrendFailuresDto o2) {
                return Period.between(o1.getEventTime(), o2.getEventTime()).getDays();
            }
        });
        return trendFailuresDtoList;
    }

    public Long getWarningListTotal() {
        return parkingStatFailuresMapper.getWarningListTotal();
    }
}
